package com.ruoyi.utils.login;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;

public class QRCodeUtil {
    private static String base64Url = "data:image/png;base64,";

    /**
     * 创建二维码
     *
     * @param url
     * @param fileName
     * @return
     * @throws IOException
     * @throws WriterException
     */
    public static String createQRCode(String url) throws IOException, WriterException {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();

        HashMap<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");

        BitMatrix bitMatrix = qrCodeWriter.encode(url, BarcodeFormat.QR_CODE, 600, 600, hints);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        MatrixToImageWriter.writeToStream(bitMatrix, "PNG", outputStream);
        Base64.Encoder encoder = Base64.getEncoder();
        String text = encoder.encodeToString(outputStream.toByteArray());
        return base64Url + text;
    }

//    public static void main(String[] args) throws IOException, WriterException {
//        System.out.println(createQRCode("https://www.baidu.com"));
//    }
}